<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\OrderAppointed;
use App\Events\OrderArbitrated;
use App\Events\OrderEmployed;
use App\Events\OrderRefunded;
use App\Events\OrderSuccess;
use App\Models\Order;
use App\Models\OrderRefund;
use App\Models\OrderStatus;
use App\Notifications\OrderNotifications\OrderArbitrateNotification;
use App\Notifications\OrderNotifications\OrderEmployedNotification;
use App\Notifications\OrderNotifications\OrderSuccessNotification;
use App\Services\IMobileService;
use App\Services\ISystemTaskService;
use DB;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class OrderArbitratedListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'order';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CacheHit  $event
     * @return void
     */
    public function handle(OrderArbitrated $event)
    {
        $refund = OrderRefund::find($event->refund_id);
        if(!$refund){
            throw new \Exception('miss refund');
        }

        if (in_array($refund->arbitrate_result_type,[Params::ORDER_ARBITRATE_RESULT_AGREE_FULL,Params::ORDER_ARBITRATE_RESULT_AGREE_PART])){
            $ret = event(new OrderRefunded($refund->id,$refund->arbitrate_result_amount));
            if (!$ret){
                throw new \Exception('trigger order refund event fail');
            }
        }

        $refund->order->merchant->notify(new OrderArbitrateNotification($refund));
        $refund->order->master->notify(new OrderArbitrateNotification($refund));
    }

    public function failed(OrderArbitrated $event, \Exception $exception)
    {
        //
    }
}
